'use strict';

module.exports = function(Action) {
  Action.observe('before save', function initResults(ctx, next) {
    var action;
    if (ctx.instance) {
      console.log('=== new action: ===');
      action = ctx.instance;
    } else {
      console.log('=== update action: ===');
      action = ctx.data;
    }

    action.initDisplayName && action.initDisplayName();

    next();
  });


  Action.prototype.initDisplayName = function () {
    var action = this;

    if (action.attributes == undefined || action.attributes.length == 0) {
      action.attributes = ['平胡'];
    }

    var displayName;
    if (action.type == '杠') {
      displayName = action.attributes[0];
    } else {
      displayName = action.type;
    }

    if (action.targets.length == 1) {
      displayName += action.targets[0].name;
    } else if (action.targets.length > 1) {
      displayName += action.targets.length + '家';
    }

    if (action.type == '胡' || action.type == '查叫') {
      action.attributes.forEach(function (attribute) {
        displayName += ' ' + attribute
      });
    }

    action.displayName = displayName;
  }

};
